import { readdirSync, readFileSync, writeFileSync } from 'fs';
import { green, red } from 'kolorist';
import { extname, resolve } from 'path';
import { IMessage } from 'qq-guild-bot';
const _path = process.cwd();

export async function delProhibited(e: { eventType: string; msg: IMessage }) {
  if (e.eventType === 'MESSAGE_CREATE') {
    let message = {};

    // 1	全体成员
    // 2	管理员
    // 4	群主/创建者
    // 5	子频道管理员
    // 没有权限
    if (
      !e.msg.member.roles.includes('4')
      // && !e.msg.member.roles.includes('5')
    ) {
      message = {
        content: `<@!${e.msg.author.id}> 无权限`,
        msg_id: e.msg.id
      };
      let { data } = await client.messageApi.postMessage(e.msg.channel_id, message);
      console.info(green(JSON.stringify(data, null, 2)));
      return true;
    }

    if (e.msg.content) {
      // trim()去除前后空格
      let content = e.msg.content.replace('/违禁词删除', '').replace(`<@!${bot.id}>`, '').trim();
      if (content !== '') {
        const files = readdirSync(resolve(_path, './plugins/违禁词/resources/prohibited/'));

        try {
          files.forEach(file => {
            if (extname(file) === '.txt') {
              let conn = '';
              readFileSync(resolve(_path, './plugins/违禁词/resources/prohibited/', file))
                .toString()
                .split('\n')
                .forEach(line => {
                  if (line && line.trim() !== '') {
                    if (line.trim() !== content) {
                      conn += line + '\n';
                    }
                  }
                });
              writeFileSync(resolve(_path, './plugins/违禁词/resources/prohibited/', file), conn);
            }
          });
          message = {
            content: `违禁词删除成功`,
            msg_id: e.msg.id
          };
          client.messageApi.postMessage(e.msg.channel_id, message).catch(err => {
            console.error(red(JSON.stringify(err, null, 2)));
          });
          return true;
        } catch (e) {
          console.error(red(JSON.stringify(e, null, 2)));
        }
      } else {
        message = {
          content: `违禁词不能为空`,
          msg_id: e.msg.id
        };
        let { data } = await client.messageApi.postMessage(e.msg.channel_id, message);
        console.info(green(JSON.stringify(data, null, 2)));
        return true;
      }
    }
  } else {
    let message = {
      content: `请在子频道发送命令，如：/违禁词添加 违禁词`,
      msg_id: e.msg.id // 可选，消息id，如果指定则会回复该消息
    };
    const { data } = await client.directMessageApi.postDirectMessage(e.msg.guild_id, message);
    console.info(green(JSON.stringify(data, null, 2)));
    return true;
  }
}
